package com.xiaozhichao.databafflesys.admin.controller;

import cn.hutool.core.io.FileUtil;
import com.xiaozhichao.databafflesys.common.domain.CommonConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author:xiaozhichao
 * @date:2021/3/26
 */
@Controller
@RequestMapping("/baffleFile")
public class BaffleFileController {

    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(String path) throws Exception {
        if(StringUtils.isEmpty(path)){
            throw new Exception("下载失败");
        }
        final String fileName = path.substring(path.lastIndexOf(CommonConstant.uri_spilt) + 1);
        try {
            byte[] bytes = FileUtil.readBytes(path);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition",
                    "attchement;filename=" + fileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            throw new Exception("下载失败");
        }
    }
}
